package com.wzdigit.wms.wms.service.core;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicGetCustomerApi;
import com.wzdigit.wms.basic.domain.basic.UserDataPermission;
import com.wzdigit.wms.basic.enums.BaseIsEnabledEnum;
import com.wzdigit.wms.basic.mapper.core.basic.UserDataPermissionMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户数据权限服务类
 * @author yangdongjie
 * @UserDataPermissionService.java
 * @2021年1月18日下午4:02:50
 */
@Service
public class UserDataPermService {
	
	@Autowired
    private WarehouseMapper warehouseMapper;
	
	@Autowired
    private UserDataPermissionMapper userDataPermissionMapper;
	
	@Reference(version = "${dubbo.consumers.basic.customer.api:1.0.0}", check = false, timeout = 300000)
	private BasicGetCustomerApi customerApi;
	
	@Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
	private BasicDataItemDetailApi dataItemDetailApi;
	
	/**
	 * 用户数据权限校验
	 * @param userId
	 * @param attr
	 * @param value
	 * @return
	 */
	public boolean existsUserDataPerm(Integer userId, String attr, Integer value) {
		QueryWrapper<UserDataPermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("USER_ID", userId);
		queryWrapper.eq("ATTR", attr);
		queryWrapper.eq("VALUE", value);
		queryWrapper.eq("STATUS", BaseIsEnabledEnum.USE.code);
		UserDataPermission one = userDataPermissionMapper.selectOne(queryWrapper);
		return one != null;
    }
	
	/**
	 * 获取用户数据权限
	 * @param <T>
	 * @param userId
	 * @param attr【WHS：仓库权限、FAC：工厂权限、OWN：货主权限、CTC：成本中心、WKC：工作中心
	 * @return
	 */
	public List<?> getPermsByUserIdAndAttr(Integer userId, String attr) {
		if ("WHS".equals(attr)) {
			return warehouseMapper.selectAllByUserIdAndWhsType(userId, null);
		} else {
			List<Integer> ids = userDataPermissionMapper.selectByUserIdAndAttr(userId, attr);
			if (ids.size() == 0) {
				return null;
			} else {
				if ("OWN".equals(attr)) {
					return customerApi.getCustomer(ids);
				} else {
					return dataItemDetailApi.getDataItemDetailByIds(ids);
				}
			}
		}
	}
}
